package com.wxs.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

//AOP 的好处  横切
@EnableWebSecurity /*开启webSecurity的支持*/
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);

        System.out.println("enter Security");
        /*链式编程*/
        /*定制请求的授权规则*/
        http.authorizeRequests().antMatchers("/").permitAll()   /*对所有人授权首页*/
                    .antMatchers("/level1/**").hasRole("vip1")
                    .antMatchers("/level2/**").hasRole("vip2")
                    .antMatchers("/level3/**").hasRole("vip3");

        //没有权限默认会到登录页
        /*定制登录页*/
        http.formLogin()
                .usernameParameter("username")
                .passwordParameter("pwd")
                .loginPage("/toLogin")
                .loginProcessingUrl("/login");

        /*开启logout*/
        http.logout().logoutSuccessUrl("/");

        //防止网站攻击  get不安全
        /*http.csrf().disable();  //关闭csrf功能*/

        /*记住我*/
        http.rememberMe().rememberMeParameter("remember");
    }

    /*定义认证规则*/
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*super.configure(auth);*/

        //在内存中定义，也可以在jdbc中去拿....
        //Spring security 5.0中新增了多种加密方式，也改变了密码的格式。
        //要想我们的项目还能够正常登陆，需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密
        //spring security 官方推荐的是使用bcrypt加密方式。

        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("wxs").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3").and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3").and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}
